package com.chookss.home.interview;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentSearchActivity;
import com.chookss.tools.NavigationTools;
import com.google.gson.reflect.TypeToken;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.InterviewRecordsEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import scut.carson_ho.searchview.EditText_Clear;

public class InterviewSearchRecordsActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.rcvHistory)
    RecyclerView rcvHistory;
    @BindView(R.id.llHistory)
    LinearLayout llHistory;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    private MyHistoryAdapter myHistoryAdapter;
    private MyInterviewRecordsAdapter myInterviewRecordsAdapter;
    private List<String> namesList = new ArrayList<>();
    private List<InterviewRecordsEntity> interviewRecordsEntities = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String keyWords="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.common_search_records);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_title_txt.setText("搜索");
        String text = new ShareUtils().getString(this, Utils.getCacheName(this,StaticClass.INTERVIEW_HISTORY), "");
        if (!Utils.isNull(text)) {
            List<String> stringList = JSONArray.parseArray(text, String.class);
            if (stringList != null) {
                namesList.addAll(stringList);
            }
            if (namesList.size() > 0) {
               llHistory.setVisibility(View.VISIBLE);
            }
        }
        rcvHistory.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rcvHistory.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        myHistoryAdapter = new MyHistoryAdapter(R.layout.item_interview_history, this, namesList);
        rcvHistory.setAdapter(myHistoryAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        myInterviewRecordsAdapter = new MyInterviewRecordsAdapter(R.layout.item_interview_records, this, interviewRecordsEntities,0);
        recyclerView.setAdapter(myInterviewRecordsAdapter);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getRecords();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getRecords();
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        add(v.getText().toString());
                        keyWords = v.getText().toString();
                        Utils.hideInputKeyboard(InterviewSearchRecordsActivity.this,etSearch);
                        llHistory.setVisibility(View.GONE);
                        llNone.setVisibility(View.GONE);
                        smrRf.setVisibility(View.VISIBLE);
                        smrRf.autoRefresh();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(Utils.isNull(s.toString())){
                    tvCancel.setText("取消");
                }else{
                    tvCancel.setText("搜索");
                }
            }
        });
        NavigationTools.setWaterMark(this, "16");
    }

    private void getRecords() {
        Map<String, String> map = new HashMap<>();
        map.put("postCode", "");
        map.put("createTime", "");
        map.put("examName", keyWords);
        map.put("companyCode",new ShareUtils().getString(this, StaticClass.COMPANYCODE,""));
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<InterviewRecordsEntity>>>() {
        }.getType(), null, Urls.getInterviewPersonList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<InterviewRecordsEntity>>() {
            @Override
            public void onSuccess(List<InterviewRecordsEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    interviewRecordsEntities.clear();
                    myInterviewRecordsAdapter.notifyDataSetChanged();
                }
                if(smrRf==null||llNone==null){
                    return;
                }
                if (data != null && data.size() > 0) {
                    interviewRecordsEntities.addAll(data);
                    myInterviewRecordsAdapter.notifyDataSetChanged();
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (interviewRecordsEntities.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }



    class MyHistoryAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;

        public MyHistoryAdapter(int layoutResId, Context context, @Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String item) {

            TextView tvName = helper.getView(R.id.tvName);
            LinearLayout llDelete = helper.getView(R.id.llDelete);
            tvName.setText(item);
            llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    removeName(helper.getItemPosition());
                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    keyWords=item;
                    etSearch.setText(item);
                    llHistory.setVisibility(View.GONE);
                    smrRf.setVisibility(View.VISIBLE);
                    smrRf.autoRefresh();
                }
            });
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.tvCancel, R.id.tvClearHistory})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvCancel:
                if("搜索".equals(tvCancel.getText().toString())){
                    add(etSearch.getText().toString());
                    keyWords = etSearch.getText().toString();
                    Utils.hideInputKeyboard(InterviewSearchRecordsActivity.this,etSearch);
                    llHistory.setVisibility(View.GONE);
                    llNone.setVisibility(View.GONE);
                    smrRf.setVisibility(View.VISIBLE);
                    smrRf.autoRefresh();
                }else{
                    finish();
                }
                break;
            case R.id.tvClearHistory:
                if(llHistory==null){
                    return;
                }
                new ShareUtils().putString(this, Utils.getCacheName(this,StaticClass.INTERVIEW_HISTORY), "");
                namesList.clear();
                llHistory.setVisibility(View.GONE);
                break;
        }
    }

    private void add(String data) {
        // 设置 Adapter
        if (!namesList.contains(data)) {
            namesList.add(data);
            saveSearchHistory();
        }
    }

    private void removeName(int position) {
        // 设置 Adapter
        if(llHistory==null){
            return;
        }
        namesList.remove(position);
        saveSearchHistory();
        if(namesList.size()>0){
            myHistoryAdapter.notifyDataSetChanged();
        }else{
            llHistory.setVisibility(View.GONE);
        }
    }

    private void saveSearchHistory() {
        if (namesList.size() > 5) {
            namesList.remove(0);
        }
        String text = JSON.toJSONString(namesList);
        new ShareUtils().putString(this, Utils.getCacheName(this,StaticClass.INTERVIEW_HISTORY), text);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (etSearch != null) {
            Utils.hideInputKeyboard(this, etSearch);
        }
    }
}
